<?php
/**
 * eg. <{pager pagesum=20}>
 */
function smarty_function_mpager($params, &$smarty)
{
    function __f1($i, $j, $c) { for ($k = $i; $k <= $j; $k++) $a[] = $c == $k ? "<li class=\"pagebarCurrent\">$k</li>" : "<li><a href=\"?" . __f2($k) . "\">$k</a></li>"; return empty($a) ? '' :  implode(' ', $a); }
    function __f2($p) { return preg_match(';(^|&)page=(\d+)($|&);i', $_SERVER["QUERY_STRING"]) ?  preg_replace(';(^|&)page=(\d+)($|&);i', '$1page=' . $p . '$3', $_SERVER["QUERY_STRING"]) : ($_SERVER["QUERY_STRING"] ? $_SERVER["QUERY_STRING"] . '&page=' . $p : 'page=' . $p); }
    ;
    $pagesum = $params['pagesum'];
	if ($pagesum < 2) return '';
    $page = !empty($_GET['page']) ? (int) $_GET['page'] : 1;
    if ($pagesum <= 6) {
	    $navleft = 2;
    	$navright = $pagesum - 1;
    }
    else if ($page <= 3) {
	    $navleft = 2;
    	$delta = 5 - $page;
    	$navright = $page + $delta;
    }
    else if ($page >= $pagesum - 3) {
    	$navright = $pagesum - 1;
    	$delta = 4 - $pagesum + $page;
	    $navleft = $page - $delta;
    }
    else {
	    $navleft = $page - 1;
    	$navright = $page + 2;
    }
    return '<div class="nav pagebar fix"><ul>'
    	. (1 == $page ?
    	"<li class=\"pagebarCurrent\">1</li>"
    	: "<li class=\"pagebarFirst\"><a href=\"?" . __f2(1) . "\">1</a></li>")
    	. ' ' . (__f1($navleft, $navright, $page)) # nav
    	. ($pagesum == $page ?
    	"<li class=\"pagebarCurrent\">$pagesum</li>"
    	: "<li class=\"pagebarLast\"><a href=\"?" . __f2($pagesum) . "\">$pagesum</a></li>")
        . '</ul></div>';
}
?>